package com.joysuch.wwyt.core.service.impl;

import cn.zlg.common.util.CollectionUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.joysuch.wwyt.bp.bean.BpDepartListBean;
import com.joysuch.wwyt.bp.entity.BpDepart;
import com.joysuch.wwyt.bp.repository.BpDepartDao;
import com.joysuch.wwyt.bp.repository.BpJobDao;
import com.joysuch.wwyt.bp.service.BpDepartService;
import com.joysuch.wwyt.common.constant.Constant;
import com.joysuch.wwyt.config.RedisClient;
import com.joysuch.wwyt.core.bean.SimpleSelectListBean;
import com.joysuch.wwyt.core.common.ajax.ResultBean;
import com.joysuch.wwyt.core.entity.*;
import com.joysuch.wwyt.core.entity.redis.DataSecurityRedisBO;
import com.joysuch.wwyt.core.enums.BaseConfigCodes;
import com.joysuch.wwyt.core.mapper.BaseRoleDataDepartAuthMapper;
import com.joysuch.wwyt.core.mapper.BaseRoleDataEmpAuthMapper;
import com.joysuch.wwyt.core.repository.BaseRoleUserLoginRoleDao;
import com.joysuch.wwyt.core.repository.BaseUserDao;
import com.joysuch.wwyt.core.service.BaseRoleDataAuthService;
import com.joysuch.wwyt.core.support.Context;
import com.joysuch.wwyt.util.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author : pp
 * @date : Created in 2021/4/13 11:15
 */
@Service
@Transactional
public class BaseRoleDataAuthServiceImpl implements BaseRoleDataAuthService {

    @Autowired
    private BaseRoleDataDepartAuthMapper departAuthMapper;
    @Autowired
    private BaseRoleDataEmpAuthMapper empAuthMapper;
    @Autowired
    private BpDepartDao bpDepartDao;
    @Autowired
    private BaseUserDao baseUserDao;
    @Autowired
    private BpDepartService departService;
    @Autowired
    private RedisClient redisClient;
    @Autowired
    private BaseRoleUserLoginRoleDao baseRoleUserLoginRoleDao;
    @Autowired
    private BpJobDao bpJobDao;
    @Autowired
    BpDepartDao deptDao;


    @Override
    public void saveDepartAuth(BaseRoleDataDepartAuth entity) {
        entity.setOrgCode(Context.getCompanyCode());
        entity.setTenentId(Context.getCurrentTenantId());
        entity.setCreateTime(new Date());
        if (entity.getDepartId() == -1) {
            entity.setCreateTime(new Date(2099, 1, 1));
        }
        //校验同一个部门id是否被重复添加权限
        BaseRoleDataDepartAuth repeat = departAuthMapper.checkRepeat(entity.getRoleId(), entity.getDepartId());
        if (repeat != null) {
            throw new IllegalArgumentException("该部门已添加过组织权限");
        }
        departAuthMapper.insert(entity);
        //更新缓存
        String redisKey = builderDataSecurityKey(Context.getCurrentTenantId(), Context.getCompanyCode());
        saveRoleDepartCache(entity.getRoleId(), null, redisKey);
    }

    @Override
    public void deleteDepartAuth(List<Long> ids) {
        if (CollectionUtils.isNotEmpty(ids)) {
            Long roleId = departAuthMapper.selectById(ids.get(0)).getRoleId();
            departAuthMapper.deleteBatch(ids);
            String redisKey = builderDataSecurityKey(Context.getCurrentTenantId(), Context.getCompanyCode());
            saveRoleDepartCache(roleId, null, redisKey);
        }
    }

    @Override
    public PageInfo<BaseRoleDataDepartAuthVo> findAllDepartAuth(Long roleId, Integer pageNum, Integer pageSize) {

        PageInfo<BaseRoleDataDepartAuthVo> pageInfo = new PageInfo<>(pageNum, pageSize);
        Page<BaseRoleDataDepartAuth> page = new Page<>(pageNum, pageSize);

        IPage<BaseRoleDataDepartAuth> historyIPage = departAuthMapper.queryByRoleId(page, roleId);
        List<BaseRoleDataDepartAuth> list = historyIPage.getRecords();

        //判断是否包含 -1 即所在组织
        List<BaseRoleDataDepartAuthVo> collect = list.stream().filter(e -> e.getDepartId() == -1).map(e -> {
            BaseRoleDataDepartAuthVo vo = new BaseRoleDataDepartAuthVo();
            BeanUtils.copyProperties(e, vo);
            vo.setDepartName("所在组织");
            return vo;
        }).collect(Collectors.toList());

        //处理正常id的部门
        List<BaseRoleDataDepartAuthVo> vos = list.stream().filter(e -> e.getDepartId() != -1).map(e -> {
            Optional<BpDepart> byId = bpDepartDao.findById(e.getDepartId());
            if (byId.isPresent()) {
                BpDepart depart = byId.get();
                BaseRoleDataDepartAuthVo vo = new BaseRoleDataDepartAuthVo();
                BeanUtils.copyProperties(e, vo);
                vo.setDepartCode(depart.getCode());
                vo.setDepartName(depart.getName());
                return vo;
            } else {
                return null;
            }
        }).collect(Collectors.toList());

        //第一頁 如果勾选了所在组织的话  就合并起来返回给前端  所在组织排第一
//        if (pageNum == 1){
        if (!CollectionUtils.isEmpty(collect)) {
            vos.addAll(0, collect);
        }
//        }

        pageInfo.setTotalCount((int) historyIPage.getTotal());
        pageInfo.setLists(vos);
        return pageInfo;
    }

    /**
     * 查询当前用户所有角色数据权限人员id
     *
     * @return
     */

    public Set<Long> findRoleDataEmpByCurUser() {
        Long userId = Context.getCurrentUser().getRealUserId();
        Long departId = curUserDepartId(userId);
        List<Long> roleIds = baseRoleUserLoginRoleDao.selectRoleIdsByUserId(userId);
        Set<Long> allEmpIds = new HashSet<>();
        allEmpIds.add(userId);

        for (Long id : roleIds) {
            allEmpIds.addAll(empAuthMapper.selectByRoleIdempAuth(id).stream().map(BaseRoleDataEmpAuth::getUserId).collect(Collectors.toList()));
        }

        return allEmpIds;
    }

    /**
     * 查询当前用户所有角色数据权限部门code
     *
     * @return
     */
    public Map<String, List<String>> findAuthDepartCodesByCurUser() {
        Long userId = Context.getCurrentUser().getRealUserId();
        Long departId = curUserDepartId(userId);
        List<Long> roleIds = baseRoleUserLoginRoleDao.selectRoleIdsByUserId(userId);

        Map<String, List<String>> allDepartCodes = new HashMap<>();

        List<BaseRoleDataDepartAuth> departAuths = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(roleIds)) {
            departAuths.addAll(departAuthMapper.queryByRoleIds(roleIds));
        }
        //不包含子部门
        Set<Long> departIdsNoChild = departAuths.stream()
                .filter(e -> e.getContainChild() == 0)
                .map(BaseRoleDataDepartAuth::getDepartId)
                .collect(Collectors.toSet());
        departIdsNoChild.add(departId);

        List<String> codeListNoChild = deptDao.findCodeListByDeptIds(new ArrayList<>(departIdsNoChild))
                .stream().map(BpDepart::getCode)
                .collect(Collectors.toList());
        allDepartCodes.put("noChild", codeListNoChild);

        //包含子部门
        Set<Long> departIdsHasChild = departAuths.stream()
                .filter(e -> e.getContainChild() == 1)
                .map(BaseRoleDataDepartAuth::getDepartId)
                .collect(Collectors.toSet());

        Set<Long> deptChildIds = new HashSet<>();
        if (CollectionUtils.isNotEmpty(departIdsHasChild)) {
            departIdsHasChild.forEach(each -> deptChildIds.addAll(departments(each)));
        }

        List<String> codeListHasChild = deptDao.findCodeListByDeptIds(new ArrayList<>(deptChildIds))
                .stream().map(BpDepart::getCode)
                .collect(Collectors.toList());
        allDepartCodes.put("hasChild", codeListHasChild);

        return allDepartCodes;
    }

    @Override
    public Set<Long> findAuthDepartIdsByCurUser() {
        Long userId = Context.getCurrentUser().getRealUserId();
        Long departId = curUserDepartId(userId);
        List<Long> roleIds = baseRoleUserLoginRoleDao.selectRoleIdsByUserId(userId);
        Set<Long> allDepartIds = new HashSet<>();
        if (CollectionUtils.isNotEmpty(roleIds)) {
            List<BaseRoleDataDepartAuth> departAuths = departAuthMapper.queryByRoleIds(roleIds);
            //不包含子部门
            Set<Long> departIdsNoChild = departAuths.stream().filter(e -> e.getContainChild() == 0).map(BaseRoleDataDepartAuth::getDepartId).collect(Collectors.toSet());
            allDepartIds.addAll(departIdsNoChild);
            //包含子部门
            Set<Long> departIdsHasChild = departAuths.stream().filter(e -> e.getContainChild() == 1).map(BaseRoleDataDepartAuth::getDepartId).collect(Collectors.toSet());
            if (CollectionUtils.isNotEmpty(departIdsHasChild)) {
                departIdsHasChild.forEach(each -> allDepartIds.addAll(departments(each)));
                if (departIdsHasChild.contains(-1L)) {
                    allDepartIds.addAll(departments(departId));
                }
            }
            Set<Long> departIds = departAuths.stream().map(BaseRoleDataDepartAuth::getDepartId).collect(Collectors.toSet());
            if (departIds.contains(-1L)) {
                allDepartIds.add(departId);
                allDepartIds.removeIf(each -> each.equals(-1L));
            }
        }
        return allDepartIds;
    }

    @Override
    public List<Long> findDepartIdsByCurUser() {
        Long userId = Context.getCurrentUser().getRealUserId();
        Long tenantId = Context.getCurrentTenantId();
        String orgCode = Context.getCompanyCode();
        return getUserDepartPerm(userId, tenantId, orgCode);
    }

    @Override
    public List<Long> findDepartIdsByUserId(Long userId, Long tenantId, String orgCode) {
        return getUserDepartPerm(userId, tenantId, orgCode);
    }

    private List<Long> getUserDepartPerm(Long userId, Long tenantId, String orgCode) {
        Long departId = curUserDepartId(userId);
        List<Long> roleIds = baseRoleUserLoginRoleDao.selectRoleIdsByUserId(userId);
        List<Long> departIds = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(roleIds)) {
            String redisKey = builderDataSecurityKey(tenantId, orgCode);
            roleIds.forEach(each -> {
                DataSecurityRedisBO dataSecurityRedisBO = redisClient.hget(redisKey, each, DataSecurityRedisBO.class);
                if (dataSecurityRedisBO == null) {
                    dataSecurityRedisBO = saveRoleDepartCache(each, null, redisKey);
                }
                if (dataSecurityRedisBO != null && CollectionUtils.isEmpty(dataSecurityRedisBO.getDepartIds())) {
                    dataSecurityRedisBO = saveRoleDepartCache(each, dataSecurityRedisBO, redisKey);
                }
                if (dataSecurityRedisBO != null) {
                    Set<Long> roleDepartIds = dataSecurityRedisBO.getDepartIds();
                    if (CollectionUtils.isNotEmpty(roleDepartIds)) {
                        departIds.addAll(roleDepartIds);
                    }
                    Boolean selfDept = dataSecurityRedisBO.getSelfDept();
                    Boolean containChild = dataSecurityRedisBO.getContainChild();
                    //组织类型为所在组织且包含子部门
                    if (selfDept != null && containChild != null && selfDept) {
                        if (containChild) {
                            departIds.addAll(departments(departId));
                        } else {
                            departIds.add(departId);
                        }
                    }
                }
            });
        }
        return departIds;
    }

    private Long curUserDepartId(Long userId) {
        Optional<BaseUser> optionalUser = baseUserDao.findById(userId);
        return optionalUser.isPresent() ? optionalUser.get().getDepartId() : 0L;
    }

    @Override
    public DataSecurityRedisBO saveRoleDepartCache(Long roleId, DataSecurityRedisBO dataSecurity, String redisKey) {
        if (dataSecurity == null) {
            dataSecurity = new DataSecurityRedisBO();
        }
        if (roleId != null) {
            List<BaseRoleDataDepartAuth> departAuths = departAuthMapper.selectByRoleId(roleId);
            if (CollectionUtils.isNotEmpty(departAuths)) {
                //更新缓存
                builderDataSecurity(departAuths, dataSecurity);
                this.saveRoleDeptToRedis(roleId, dataSecurity, redisKey);
            } else {
                redisClient.removeMapKey(redisKey, roleId);
            }
        }
        return dataSecurity;
    }

    @Override
    public void initTenantRoleDepartCache() {
        //更新当前租户
        LambdaQueryWrapper<BaseRoleDataDepartAuth> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(BaseRoleDataDepartAuth::getTenentId, Context.getCurrentTenantId());
        wrapper.likeRight(BaseRoleDataDepartAuth::getOrgCode, Context.getCompanyCode());
        List<BaseRoleDataDepartAuth> departAuths = departAuthMapper.selectList(wrapper);
        initRoleDepartCache(departAuths);
    }

    @Override
    public ResultBean findJobForReport() {
        Set<Long> jobIds = departAuthMapper.selectJobForReport(Context.getCurrentTenantId(), Context.getCurrentOrgCode());
        ArrayList<SimpleSelectListBean> select = new ArrayList<>();
        jobIds.forEach(each -> {
            select.add(new SimpleSelectListBean(each, bpJobDao.getNameById(each)));
        });
        return ResultBean.success(select);
    }

    @Override
    public void initAllRoleDepartCache() {
        //全量更新
        List<BaseRoleDataDepartAuth> departAuths = departAuthMapper.selectAllList();
        initRoleDepartCache(departAuths);
    }

    private void initRoleDepartCache(List<BaseRoleDataDepartAuth> departAuths) {
        Map<Long, List<BaseRoleDataDepartAuth>> roleDepartMap = departAuths.stream().collect(Collectors.groupingBy(BaseRoleDataDepartAuth::getRoleId));
        //更新缓存
        roleDepartMap.keySet().forEach(roleId -> {
            DataSecurityRedisBO dataSecurity = builderDataSecurity(roleDepartMap.get(roleId), new DataSecurityRedisBO());
            saveInitRoleDeptToRedis(roleId, dataSecurity, roleDepartMap.get(roleId));
        });
    }

    private DataSecurityRedisBO builderDataSecurity(List<BaseRoleDataDepartAuth> departAuths, DataSecurityRedisBO dataSecurity) {
        if (CollectionUtils.isNotEmpty(departAuths)) {
            boolean selfDept = dataSecurity.getSelfDept() != null && dataSecurity.getSelfDept();
            boolean containChild = dataSecurity.getContainChild() != null && dataSecurity.getContainChild();
            Set<Long> allDepartIds = getDepartIds(departAuths);
            //组织类型为所在组织
            Optional<BaseRoleDataDepartAuth> optionalSelfDepart = departAuths.stream().filter(each -> Constant.SELF_DEPART.equals(each.getDepartId())).findFirst();
            if (optionalSelfDepart.isPresent()) {
                allDepartIds.removeIf(each -> each.equals(Constant.SELF_DEPART));
                selfDept = true;
            }
            Optional<BaseRoleDataDepartAuth> optionalContainChildDepart = departAuths.stream().filter(each -> Constant.DEPART_AUTH_CONTAIN_CHILD.equals(each.getContainChild())).findFirst();
            if (optionalContainChildDepart.isPresent()) {
                containChild = true;
            }
            dataSecurity.setDepartIds(allDepartIds);
            dataSecurity.setSelfDept(selfDept);
            dataSecurity.setContainChild(containChild);
        }
        return dataSecurity;
    }

    private Set<Long> getDepartIds(List<BaseRoleDataDepartAuth> departAuths) {
        Set<Long> allDepartIds = new HashSet<>();
        Map<Integer, List<BaseRoleDataDepartAuth>> roleDeptMap = departAuths.stream().collect(Collectors.groupingBy(BaseRoleDataDepartAuth::getContainChild));
        //包含子部门
        if (CollectionUtils.isNotEmpty(roleDeptMap.get(Constant.DEPART_AUTH_CONTAIN_CHILD))) {
            roleDeptMap.get(Constant.DEPART_AUTH_CONTAIN_CHILD).forEach(each -> {
                allDepartIds.addAll(departments(each.getDepartId()));
            });
        }
        //不包含子部门
        if (CollectionUtils.isNotEmpty(roleDeptMap.get(Constant.DEPART_AUTH_NOT_CONTAIN_CHILD))) {
            roleDeptMap.get(Constant.DEPART_AUTH_NOT_CONTAIN_CHILD).forEach(each -> allDepartIds.add(each.getDepartId()));
        }
        return allDepartIds;
    }

    private void saveRoleDeptToRedis(Long roleId, DataSecurityRedisBO dataSecurity, String redisKey) {
        redisClient.hput(redisKey, roleId, JSON.toJSONString(dataSecurity));
    }

    private void saveInitRoleDeptToRedis(Long roleId, DataSecurityRedisBO dataSecurity, List<BaseRoleDataDepartAuth> roleDeparts) {
        if (CollectionUtils.isNotEmpty(roleDeparts)) {
            Long tenantId = roleDeparts.get(0).getTenentId();
            String orgCode = roleDeparts.get(0).getOrgCode();
            String redisKey = String.format(BaseConfigCodes.ROLE_DATA_SECURITY_REDIS_KEY, tenantId, orgCode);
            redisClient.hput(redisKey, roleId, JSON.toJSONString(dataSecurity));
        }
    }

    private String builderDataSecurityKey(Long tenantId, String orgCode) {
        return String.format(BaseConfigCodes.ROLE_DATA_SECURITY_REDIS_KEY, tenantId, orgCode);
    }


    @Override
    public void saveEmpAuth(List<BaseRoleDataEmpAuth> entitys) {
        BaseRoleDataEmpAuth empAuth = entitys.get(0);
        //先删除再保存
//        empAuthMapper.deleteByRoleId(empAuth.getRoleId());
        List<BaseRoleDataEmpAuth> savedAll = empAuthMapper.selectByRoleIdempAuth(empAuth.getRoleId());
        //删除原来存储  本次未勾选的员工
        List<Long> savedUserId = savedAll.stream().map(BaseRoleDataEmpAuth::getUserId).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(savedUserId)) {
            List<Long> toSaveUserId = entitys.stream().map(BaseRoleDataEmpAuth::getUserId).collect(Collectors.toList());
            //求差集  得出待删除的userId
            savedUserId.removeAll(toSaveUserId);
            if (CollectionUtils.isNotEmpty(savedUserId)) {
                empAuthMapper.deleteByRoleIdAndUserIds(empAuth.getRoleId(), savedUserId);
            }
        }

        //求出本次新增的员工id
        List<Long> entityUserId = entitys.stream().map(BaseRoleDataEmpAuth::getUserId).collect(Collectors.toList());
        List<Long> dbUserId = savedAll.stream().map(BaseRoleDataEmpAuth::getUserId).collect(Collectors.toList());
        entityUserId.removeAll(dbUserId);
        if (CollectionUtils.isNotEmpty(dbUserId)) {
            List<BaseRoleDataEmpAuth> collect = entitys.stream().filter(e -> !dbUserId.contains(e.getUserId())).collect(Collectors.toList());
            collect.forEach(e -> {
                e.setOrgCode(Context.getCompanyCode());
                e.setTenentId(Context.getCurrentTenantId());
                e.setCreateTime(new Date());
                if (e.getUserId() == -1) {
                    e.setCreateTime(new Date(2099, 1, 1));
                }
                empAuthMapper.insert(e);
            });
        } else {
            //全部新增
            entitys.forEach(entity -> {
                entity.setOrgCode(Context.getCompanyCode());
                entity.setTenentId(Context.getCurrentTenantId());
                entity.setCreateTime(new Date());
                if (entity.getUserId() == -1) {
                    entity.setCreateTime(new Date(2099, 1, 1));
                }
                empAuthMapper.insert(entity);
            });
        }


    }

    @Override
    public void deleteEmpAuth(List<Long> ids) {
        empAuthMapper.deleteBatch(ids);
    }

    @Override
    public ResultBean findAllEmpAuth(Long roleId, Integer pageNum, Integer pageSize) {

        Page<BaseRoleDataEmpAuth> page = new Page<>(pageNum, pageSize);
        LambdaQueryWrapper<BaseRoleDataEmpAuth> lq = new QueryWrapper<BaseRoleDataEmpAuth>()
                .lambda().eq(BaseRoleDataEmpAuth::getRoleId, roleId).orderByDesc(BaseRoleDataEmpAuth::getCreateTime).orderByDesc(BaseRoleDataEmpAuth::getId);

        IPage<BaseRoleDataEmpAuth> baseRoleDataEmpAuthIPage = empAuthMapper.selectPage(page, lq);
        List<BaseRoleDataEmpAuth> list = baseRoleDataEmpAuthIPage.getRecords();
        //处理正常人员的id
        List<BaseRoleDataEmpAuthVo> vos = list.stream().map(e -> {
            if (e.getUserId() != -1) {
                Optional<BaseUser> byId = baseUserDao.findById(e.getUserId());
                if (byId.isPresent()) {
                    BaseUser baseUser = byId.get();
                    BaseRoleDataEmpAuthVo vo = new BaseRoleDataEmpAuthVo();
                    BeanUtils.copyProperties(e, vo);
                    vo.setEmpCode(baseUser.getCode());
                    vo.setEmpName(baseUser.getRealName());
                    return vo;
                } else {
                    return null;
                }
            } else if (e.getUserId() == -1) {
                BaseRoleDataEmpAuthVo vo = new BaseRoleDataEmpAuthVo();
                BeanUtils.copyProperties(e, vo);
                vo.setEmpName("本人");
                return vo;
            }
            return null;
        }).collect(Collectors.toList());

        return ResultBean.pageData(vos, (int) baseRoleDataEmpAuthIPage.getTotal());
    }

    @Override
    public Long[] getUserIds(Long roleId) {
        List<Long> ids = empAuthMapper.getUserIds(roleId);
        Long[] longs = new Long[ids.size()];
        ids.toArray(longs);
        return longs;
    }

    @Override
    public Set<Long> getSummaryUserIds(Long role, Long departId) {

        Set<Long> ids = new HashSet<>();
        //所在组织 -1
        List<BaseRoleDataDepartAuth> dataDepartAuths = departAuthMapper.selectByRoleId(role);
        //指定部门
        List<Long> deparIds = dataDepartAuths.stream().filter(e -> e.getDepartId() != -1 && e.getContainChild() == 0).map(BaseRoleDataDepartAuth::getDepartId).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(deparIds)) {
            List<Long> userIds = baseUserDao.findIdByDepartIdIn(deparIds);
            ids.addAll(userIds);
        }
        //指定部门 并且 勾选包含子部门
        List<Long> containDeparIds = dataDepartAuths.stream().filter(e -> e.getDepartId() != -1 && e.getContainChild() == 1).map(BaseRoleDataDepartAuth::getDepartId).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(containDeparIds)) {
            if (CollectionUtils.isNotEmpty(containDeparIds)) {
                containDeparIds.forEach(e -> {
                    List<Long> departments = departments(e);
                    List<Long> userIds = baseUserDao.findIdByDepartIdIn(departments);
                    ids.addAll(userIds);
                });
            }
        }
        //所在组织
        List<Long> departIdSelf = dataDepartAuths.stream().filter(e -> e.getDepartId() == -1 && e.getContainChild() == 0).map(BaseRoleDataDepartAuth::getDepartId).collect(Collectors.toList());
        if (departIdSelf.size() > 0) {
            //说明勾选所在组织
            List<Long> selfUserIds = baseUserDao.findIdByDepartId(departId);
            ids.addAll(selfUserIds);
        }
        //所在组织 并且包含子部门
        List<Long> containDepartIdSelf = dataDepartAuths.stream().filter(e -> e.getDepartId() == -1 && e.getContainChild() == 1).map(BaseRoleDataDepartAuth::getDepartId).collect(Collectors.toList());
        if (containDepartIdSelf.size() > 0) {
            List<Long> departments = departments(departId);
            List<Long> userIds = baseUserDao.findIdByDepartIdIn(departments);
            ids.addAll(userIds);
        }
        return ids;
    }

    /**
     * 查询本部门 及 子部门
     *
     * @param id
     * @return
     */
    public List<Long> departments(Long id) {
        List<Long> ids = new ArrayList<>();
        ids.add(id);
        ids.addAll(this.findChild(id));
        return ids;
    }

    /**
     * 查询子部门
     *
     * @param id
     * @return
     */
    private List<Long> findChild(Long id) {
        List<Long> ids = new ArrayList<>();
        Pageable of = PageRequest.of(0, Integer.MAX_VALUE);
        List<BpDepartListBean> contents = departService.get(id, of).getContent();
        contents.forEach(c -> {
            ids.add(c.getId());
        });
        return ids;
    }

    @Override
    public Set<Long> getEmpAuthUserIds(Long role, Long userId) {

        Set<Long> total = new HashSet<>();
        //本人 -1
        List<Long> empIds = empAuthMapper.getUserIds(role);
        List<Long> collect = empIds.stream().filter(e -> e != -1).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(collect)) {
            total.addAll(collect);
        }
        if (empIds.contains(-1L)) {
//            total.add(Context.getCurrentUserId());
            total.add(userId);
        }
        return total;
    }
}
